package com.wang.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.mall.bean.SmsSeckillSkuRelation;
import com.wang.mall.mapper.SmsSeckillSkuRelationMapper;
import com.wang.mall.service.ProductService;
import com.wang.mall.service.SmsSeckillSkuRelationService;
import com.wang.mall.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Service
public class SmsSeckillSkuRelationServiceImpl extends ServiceImpl<SmsSeckillSkuRelationMapper, SmsSeckillSkuRelation> implements SmsSeckillSkuRelationService {

    @Autowired
    private ProductService productService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        String promotionSessionId = (String) params.get("promotionSessionId");

        Long curPage = Long.parseLong((String) params.get("page"));
        Long limit = Long.parseLong((String) params.get("limit"));

        LambdaQueryWrapper<SmsSeckillSkuRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(!StringUtils.isEmpty(promotionSessionId) && !promotionSessionId.equals("0"), SmsSeckillSkuRelation::getPromotionSessionId, promotionSessionId)
                .eq(!StringUtils.isEmpty(key), SmsSeckillSkuRelation::getId, key)
                .eq(!StringUtils.isEmpty(key), SmsSeckillSkuRelation::getPromotionId, key);

        IPage<SmsSeckillSkuRelation> page = this.page(
                new Page<SmsSeckillSkuRelation>(curPage, limit),
                queryWrapper
        );

        List<SmsSeckillSkuRelation> records = page.getRecords();

        for (SmsSeckillSkuRelation record : records) {
            String name = productService.getById(record.getSkuId()).getName();
            record.setProductName(name);
        }

        page.setRecords(records);
        return new PageUtils(page);
    }
}
